<template>
  <HeaderNav/>
  <article>
    <!-- 网站主体 -->
    <div id="main">
      <section class="ct">
        <!-- 上传表单-->
        <div class="upload">
          <h1>上传资源<em>声明：请确保您上传的内容合法合规，涉及侵权内容将会被移除，详见<a>《爱下载资源共享规则》</a></em>
          </h1>
          <form>
            <p class="file">
              <input type="file" name="resource" @change="handlerFile">
              <!-- 上传后的效果 -->
              <span class="t2" v-if="upload.state">
								<img :src="getExt(upload.ext)"/>
								<b>{{ upload.name }}</b>
								<a>重新上传</a>
							</span>
              <span class="t1" v-else>点击上传、文件小于1000MB（请不要上传存在侵权的资源哦！）</span>
            </p>

            <p>
              <label><em>*</em>资源名称：</label>
              <input class="upt" type="text" name="resourceName" v-model="upload.name" placeholder="请输入资源名"/>
              <em></em> <!-- 显示错误信息  -->
            </p>
            <p>
              <label>资源描述：</label>
              <textarea class="area" v-model="upload.resourceDesc" placeholder="简要介绍一下资源内容"></textarea>
            </p>

            <p>
              <label><em>*</em>关键词：</label>
              <span class="key-tag">
								<a class="key">
									<span v-for="(key, index) in upload.keywords" :key="key"
                        @click="upload.keywords.splice(index, 1)">{{ key }}</span>
									
									<input type="text" v-if="editKey"  @blur="addKeywords"/>
								</a>
								<span class="key-tag-msg" v-show="upload.keywords.length < 5">
									<button type="button" class="keywords add" @click="editKey=true">添加标签</button>
									<i class="lb">失去焦点后自动创建标签</i>
								</span>
							</span>
              <span class="source-tag-msg">最多添加5个标签，每个标签不超过16个字</span>
            </p>

            <div class="source-type-div">
              <p>
                <label><em>*</em>所属分类：</label>
                <select class="upt source-type source-type-down" v-model="upload.typeId">
                  <optgroup v-for="item in resourceTypes" :key="item.id" :label="item.name">
                    <option v-for="rtype in item.children" :key="rtype.id" :value="rtype.id">{{ rtype.name }}</option>
                  </optgroup>
                </select>
              </p>
            </div>

            <p>
              <label><em>*</em>资源分：</label>
              <select class="upt" id="sel" name="score" v-model="upload.score">
                <option v-for="(n , index) in 11" :key="index" :value="index">{{ index }}</option>
              </select>
            </p>

            <p>
              <label>验证码：</label>
              <input class="upt captcha" type="text" name="code" v-model="captchaCode"
                      placeholder="请输入验证码,如果看不清，点击验证码进行刷新"/>
              <img class="captcha" style="cursor: pointer" :src="$api.captchaCodeUrl()"
                   @click.stop.prevent="$event.target.src = $api.captchaCodeUrl()"/>
              <em></em>
            </p>

            <p><label class="btn"><a class="btn" @click="handleResource">提交</a></label></p>
          </form>
        </div>
      </section>
    </div>
  </article>
  <Footer/>
</template>

<script>
import HeaderNav from "../components/HeaderNav.vue";
import Footer from "../components/Footer.vue";

export default {
  components: {
    HeaderNav,
    Footer,
  },
  data() {
    return {
      captchaCode: null , // 验证码
      editKey: false, // 是否进行编辑关键字
      upload: {
        state: false,  // 是否上传了文件
        name: null,  // 存储上传文件名
        size: 0,    // 存储上传文件大小
        ext: null,  // 存储后缀名
        url: null,  // 存储上传后的地址
        keywords: [], // 关键字
        resourceDesc: null ,
        score: 0 ,
        typeId: null ,
      },
      resourceTypes: [],
    }
  },
  created() {
     this.$api.queryResourceTypeList().then(ret=> {
         if (ret.status) {
            this.resourceTypes = this.convertResourceTypeStruct(ret.list, null);
         }
     }) ;
  },
  methods: {
    convertResourceTypeStruct(list, pid) {
      // 获取一级子节点
      let oneTypes = list.filter(type => type.pid == pid) ;
      // 递归 获取
      return oneTypes.map(type => {
        let children = this.convertResourceTypeStruct(list, type.id) ;
        return {
          id: type.id , name: type.name ,  pid: type.pid , children
        }
      })
    },
    handlerFile(event) {
      this.upload.state = true;
      // 获取上传的文件对象
      let file = event.target.files[0];

      this.upload.name = file.name;
      // 获取文件名 和后缀
      let index = -1;
      if ((index = file.name.lastIndexOf(".")) !== -1) {
        this.upload.name = file.name.substring(0, index);
        this.upload.ext = file.name.substring(index + 1);
      }
      // 设置 上传的大小
      this.upload.size = file.size;

      this.$toastr.warning("资源正在上传中...", "", {timeOut: 0, progressBar: true, onShown: () => {
          // 发送异步请求， 上传头像
          this.$api.uploadResource(file).then(ret => {
            if (ret.status) {
              this.upload.url = ret.data;
            }
            this.$toastr.clear();
          })
        }
      })
    },
    getExt(ext) {
      let supportExts = ["doc", "docx", "exe", "gif", "gz", "html", "md", "mp4", "pdf", "png", "ppt", "pptx", "rar", "rmvb", "txt", "wps", "xls", "xlsx", "zip", "7z", "avi", "bmp"];
      let fileExt = ext;
      if (!supportExts.includes(ext)) {
        fileExt = "unknow";
      }
      // 不能使用异步函数，否则会返回一个Promise
      return new URL("../assets/images/" + fileExt + ".svg", import.meta.url).href;
    },
    addKeywords(event) {
      // 去除空格 后，判断长度是否 大于16, 是否包含特殊字符 :: , 是否已经存在
      let keyword = event.target.value.trim();
      if (keyword == "") {
        this.editKey = false;
        return;
      }

      if (keyword.indexOf("::") != -1) {
        this.$toastr.warning("关键字中包含特殊字符::", "", {timeOut: 1000});
        return;
      }

      if (keyword.length > 16) {
        this.$toastr.warning("关键字过长", "", {timeOut: 1000});
        return;
      }

      if (this.upload.keywords.includes(keyword)) {
        this.$toastr.warning("关键字已存在", "", {timeOut: 1000});
        return;
      }
      this.editKey = false;
      // 添加关键字
      this.upload.keywords.push(keyword);
    },
    handleResource() {
       this.$api.saveResource({...this.upload, code: this.captchaCode}).then(ret=> {
          if (ret.status) {
            this.$toastr.success("资源已经上传成功、系统会在三个工作日内完成资源的审核、请您耐心等待");
            // 清空所有内容
            this.upload = {
                  state: false,  // 是否上传了文件
                  name: null,  // 存储上传文件名
                  size: 0,    // 存储上传文件大小
                  ext: null,  // 存储后缀名
                  url: null,  // 存储上传后的地址
                  keywords: [], // 关键字
                  resourceDesc: null ,
                  score: 0 ,
                  typeId: null ,
            };
            this.captchaCode = null ;
          }else {
            for (let err in ret.error) {
              this.$toastr.error(ret.error[err]);
            }
            this.$toastr.error(ret.message);
          }
       }) ;
    }
  }
}

</script>

<style>
</style>